package com.neuedu.yyzx.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.neuedu.yyzx.entity.User;
import org.springframework.util.StringUtils;

public class JWTUtils {
    static final String SECRET = "dsgfdhfgh4658465^&R^%&^%&^THJVBJNBJN";

    /**
     * 加密token
     * @param user
     * @return
     * @throws IllegalArgumentException
     */
    public static  String encode(User user) throws  IllegalArgumentException{

        if(user == null){
            throw new IllegalArgumentException("用户信息不能为空");
        }

        String token = JWT.create()
                // .withExpiresAt(new Date(System.currentTimeMillis()))  //设置过期时间
                .withClaim("usernamne",user.getUsername())
                .withClaim("logintime",System.currentTimeMillis())
                .sign(Algorithm.HMAC256(SECRET));  //使用HMAC算法，111111作为密钥加密
        return token;
    }

    /**
     * 校验并获取 payload 信息
     * @param token
     * @return
     * @throws IllegalArgumentException
     */
    public static DecodedJWT decode(String token) throws  IllegalArgumentException{
        if(!StringUtils.hasText(token)){
            throw new IllegalArgumentException("token 不能为空");
        }


        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = jwtVerifier.verify(token);
        }catch (Exception e){
            e.printStackTrace();
        }

        return decodedJWT;
    }
}
